use crate::core::control::counter::Counter;
use std::path::Path;
use std::io;
use crate::core::control::config::Config;
use crate::core::analysis::matching::MatchMachine;
use std::io::{BufReader, BufRead, Lines};
use std::fs::File;
use crate::core::base;

/// 控制中心
pub struct Center {
    /// 程序计数器
    counter: Counter,
    /// 全局配置
    config: Config,
    /// 比对器
    match_machine: MatchMachine,
}

impl Center {
    pub fn new(config: Config) -> Self {
        Self {
            counter: Counter::default(),
            config,
            match_machine: MatchMachine::default(),
        }
    }
    pub fn config(&self) -> &Config { &self.config }

    /// 控制中心的执行方法
    pub fn run(&mut self, path_addr: &str) {
        // 获取路径
        let path = Path::new(path_addr);
        let yuzu = path.to_str().unwrap();
        // 按行读取文件
        let lines = read_lines(path).unwrap();
        for line in lines.flatten() {
            base::log().debug(format!("[{}]  {}\t| {}", path_addr, self.counter.current(), line));
            // 比对器进行比对执行 并且返回行状态
            let status = self.match_machine.match_line(yuzu, &line);
            base::log().debug(format!("exec line status : {}", status));
            // 计数器行数 +1
            self.counter.next();
        }
        // 展开释放
        let free = self.match_machine.buffer_free();
        base::log().debug(format!("buffered unused lines free : {:?}", free));
    }
}

fn read_lines<P>(path: P) -> io::Result<Lines<BufReader<File>>>
    where P: AsRef<Path>
{
    let file = File::open(path)?;
    Ok(BufReader::new(file).lines())
}